package com.afishing.servlet;

import com.afishing.dao.UserDao;
import com.afishing.dao.impl.UserDaoImpl;
import com.afishing.entity.User;
import com.afishing.utils.JDBCUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet(name = "loginServlet", value = "/login-servlet")
public class LoginServlet extends HttpServlet {

    UserDao userDao = new UserDaoImpl();


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {//设置请求和响应的编码

        ServletContext application=this.getServletContext();

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        User user = null;

        //查看数据库中是否有该用户
        //            loginFlag = JDBCUtil.query("select * from user where username=? and password=?", username, password);
        user = userDao.getUserByUsernameAndPassword(username, password);

        // 现在把登录判断逻辑移到filter中了
        if (user!= null) {
            // 登录成功，将用户信息存入session
            HttpSession session = request.getSession();
//            session.setAttribute("username", username);
//            System.out.println(session.getAttribute("username"));
//            session.setAttribute("password", password);
            session.setAttribute("user", user);
            // 登录成功后将用户信息存入application
            ArrayList users = (ArrayList) application.getAttribute("users");
            if (users == null) {
                users = new ArrayList();
                application.setAttribute("users", users);
            }
            ArrayList msgs = (ArrayList) application.getAttribute("msgs");
            if (msgs == null) {
                msgs = new ArrayList();
                application.setAttribute("msgs", msgs);
            }
            users.add(user);
            msgs.add(user.getUsername() + "进入了聊天室");
            // 判断是否记住密码
            if (rememberMe != null){
                // 如果cookie已存在，则不用再次创建
                Cookie[] cookies = request.getCookies();
                boolean flag = false;
                for (Cookie cookie : cookies) {
                    if ("username".equals(cookie.getName()) && "password".equals(cookie.getName())&& "rememberMe".equals(cookie.getName())) {
                        flag = true;
                        break;
                    }
                }
                if (!flag){
                    Cookie userCookie = new Cookie("username", URLEncoder.encode(username, "UTF-8"));
                    Cookie passCookie = new Cookie("password", URLEncoder.encode(password, "UTF-8"));
                    Cookie rememberMeCookie = new Cookie("rememberMe", rememberMe);
                    //保存30天
                    userCookie.setMaxAge(60 * 60 * 24 * 30);
                    passCookie.setMaxAge(60 * 60 * 24 * 30);
                    rememberMeCookie.setMaxAge(60 * 60 * 24 * 30);
                    response.addCookie(userCookie);
                    response.addCookie(passCookie);
                    response.addCookie(rememberMeCookie);
                }
            }else{
                // 不记住密码则删除所存的Cookie
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if ("username".equals(cookie.getName()) || "password".equals(cookie.getName())|| "rememberMe".equals(cookie.getName())) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }
            response.sendRedirect("navbar.html");
            // 登录成功后跳forward到welcome.jsp
        } else {
            // 登录失败，返回登录页面
            response.sendRedirect("index.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}